﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhotgalleryEntities;

namespace photogalleryMVC
{
    public class FilestreamResult:ActionResult
    {


        private const int _bufSize = 4096;
        private IStorageResult _result;
        private string _contentType;

        public FilestreamResult  (IStorageResult result,string contentType )
        {
            if (result == null)
                throw new ArgumentNullException();
            if (String.IsNullOrEmpty(contentType))
                throw new ArgumentNullException();
            _result = result;
            _contentType = contentType;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            
            if (context==null )
                throw new ArgumentNullException();
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = _contentType;
            using (Stream stream = _result.ResultStream )
            {
                byte[] buffer = new byte[_bufSize ];
                int bytesRead;
                while (true )
                {
                    bytesRead = stream.Read(buffer, 0, _bufSize);
                    if (bytesRead == 0)
                        break;
                    response.OutputStream.Write(buffer, 0, bytesRead);
                }
            }
            response.End();
            _result.Dispose();
        }
    }
}